<template>
  <div class="system-bg">
    <el-card class="user-card" shadow="hover">
      <div slot="header" class="card-header-vertical">
        <div class="header-title">分支管理</div>
        <div class="header-btn-group right">
          <el-button class="add-btn" type="primary" @click="onShowAdd">
            <i class="el-icon-plus"></i> 新增分支
          </el-button>
        </div>
      </div>
      <el-table :data="list" style="width:100%" class="user-table" highlight-current-row>
        <el-table-column prop="clanName" label="家族名称" width="120" />
        <el-table-column prop="name" label="分支名称" />
        <el-table-column prop="leaderName" label="负责人" width="120" />
        <el-table-column prop="description" label="简介" show-overflow-tooltip />
        <el-table-column label="操作" width="260">
          <template slot-scope="scope">
            <div class="action-btn-group">
              <el-button size="mini" class="edit-btn" @click="edit(scope.row)">编辑</el-button>
              <el-button size="mini" class="delete-btn" @click="remove(scope.row)">删除</el-button>
              <el-button size="mini" class="detail-btn" @click="goDetail(scope.row)">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        :page-size="size"
        :current-page="current"
        @current-change="load"
        @size-change="handleSizeChange"
        layout="total, prev, pager, next, jumper, ->, sizes"
        :page-sizes="[10, 20, 50, 100]"
        class="user-pagination"
      />
    </el-card>
    <el-dialog :visible.sync="showAdd" title="新增分支" class="fade-dialog custom-dialog" :close-on-click-modal="false" width="700px">
      <el-form :model="form" label-width="90px" class="dialog-form">
        <el-form-item label="选择家族">
          <el-select v-model="form.clanId" placeholder="请选择家族" style="width: 100%;">
            <el-option
              v-for="clan in clanList"
              :key="clan.id"
              :label="clan.name"
              :value="clan.id"
            >
              <span style="float: left">{{ clan.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ clan.description || '暂无描述' }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分支名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="选择负责人">
          <el-select v-model="form.leaderId" placeholder="请选择负责人" style="width: 100%;">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            >
              <span style="float: left">{{ user.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.email || '暂无邮箱' }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" label-width="90px" class="nowrap-label"><el-input v-model="form.description" type="textarea" :rows="2" /></el-form-item>
        <el-form-item label="迁徙路线">
          <div style="margin-bottom:8px;">
            <div style="position:relative;">
              <el-input
                v-model="searchKeywordAdd"
                @input="onSearchInputAddDebounced"
                clearable
                style="width: 350px; margin-bottom: 4px;"
              />
              <ul v-if="searchResultsAdd && searchResultsAdd.length" class="suggest-list">
                <li v-for="item in searchResultsAdd" :key="item.id" @mousedown="onSelectPlaceAdd(item)">
                  <span>{{item.name}}</span>
                  <span style="color:#888;font-size:12px;">{{item.address}}</span>
                </li>
              </ul>
            </div>
          </div>
          <div style="height:300px;">
            <div id="migrationMap" style="width:100%;height:100%;border-radius:8px;overflow:hidden;"></div>
          </div>
          <div style="margin:8px 0;">
            <el-tag
              v-for="(point, idx) in form.migrationRoute"
              :key="idx"
              style="margin:2px"
            >{{point.lng}},{{point.lat}}</el-tag>
            <el-button size="mini" @click="clearRoute" style="margin-left:8px;">清空路线</el-button>
          </div>
        </el-form-item>
        <el-form-item label="地图标记">
          <div style="margin-bottom:8px;">
            <div style="position:relative;">
              <el-input
                v-model="searchKeywordMarkerAdd"
                @input="onSearchInputMarkerAddDebounced"
                clearable
                style="width: 350px; margin-bottom: 4px;"
              />
              <ul v-if="searchResultsMarkerAdd && searchResultsMarkerAdd.length" class="suggest-list">
                <li v-for="item in searchResultsMarkerAdd" :key="item.id" @mousedown="onSelectMarkerPlaceAdd(item)">
                  <span>{{item.name}}</span>
                  <span style="color:#888;font-size:12px;">{{item.address}}</span>
                </li>
              </ul>
            </div>
          </div>
          <div style="height:200px;">
            <div id="markerMap" style="width:100%;height:100%;border-radius:8px;overflow:hidden;"></div>
          </div>
          <div style="margin:8px 0;">
            <el-tag v-if="form.mapMarker">
              {{form.mapMarker.lng}},{{form.mapMarker.lat}}
            </el-tag>
            <el-button size="mini" @click="clearMarker" style="margin-left:8px;">清空标记</el-button>
          </div>
        </el-form-item>
        <el-form-item label="地图权限设置" label-width="90px" class="nowrap-label"><el-input v-model="form.permission" placeholder="JSON格式" type="textarea" :rows="2" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAdd=false">取消</el-button>
        <el-button type="primary" @click="add">确定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑弹窗可按需扩展地图功能 -->
    <el-dialog :visible.sync="showEdit" title="编辑分支" class="fade-dialog custom-dialog" :close-on-click-modal="false" width="700px">
      <el-form :model="form" label-width="90px" class="dialog-form">
        <el-form-item label="选择家族">
          <el-select v-model="form.clanId" placeholder="请选择家族" style="width: 100%;">
            <el-option
              v-for="clan in clanList"
              :key="clan.id"
              :label="clan.name"
              :value="clan.id"
            >
              <span style="float: left">{{ clan.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ clan.description || '暂无描述' }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分支名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="选择负责人">
          <el-select v-model="form.leaderId" placeholder="请选择负责人" style="width: 100%;">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            >
              <span style="float: left">{{ user.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.email || '暂无邮箱' }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" label-width="90px" class="nowrap-label"><el-input v-model="form.description" type="textarea" :rows="2" /></el-form-item>
        <el-form-item label="迁徙路线">
          <div style="margin-bottom:8px;">
            <div style="position:relative;">
              <el-input
                v-model="searchKeywordEdit"
                @input="onSearchInputEditDebounced"
                clearable
                style="width: 350px; margin-bottom: 4px;"
              />
              <ul v-if="searchResultsEdit && searchResultsEdit.length" class="suggest-list">
                <li v-for="item in searchResultsEdit" :key="item.id" @mousedown="onSelectPlaceEdit(item)">
                  <span>{{item.name}}</span>
                  <span style="color:#888;font-size:12px;">{{item.address}}</span>
                </li>
              </ul>
            </div>
          </div>
          <div style="height:300px;">
            <div id="migrationMapEdit" style="width:100%;height:100%;border-radius:8px;overflow:hidden;"></div>
          </div>
          <div style="margin:8px 0;">
            <el-tag
              v-for="(point, idx) in form.migrationRoute"
              :key="idx"
              style="margin:2px"
            >{{point.lng}},{{point.lat}}</el-tag>
            <el-button size="mini" @click="clearRouteEdit" style="margin-left:8px;">清空路线</el-button>
          </div>
        </el-form-item>
        <el-form-item label="地图标记">
          <div style="margin-bottom:8px;">
            <div style="position:relative;">
              <el-input
                v-model="searchKeywordMarkerEdit"
                @input="onSearchInputMarkerEditDebounced"
                clearable
                style="width: 350px; margin-bottom: 4px;"
              />
              <ul v-if="searchResultsMarkerEdit && searchResultsMarkerEdit.length" class="suggest-list">
                <li v-for="item in searchResultsMarkerEdit" :key="item.id" @mousedown="onSelectMarkerPlaceEdit(item)">
                  <span>{{item.name}}</span>
                  <span style="color:#888;font-size:12px;">{{item.address}}</span>
                </li>
              </ul>
            </div>
          </div>
          <div style="height:200px;">
            <div id="markerMapEdit" style="width:100%;height:100%;border-radius:8px;overflow:hidden;"></div>
          </div>
          <div style="margin:8px 0;">
            <el-tag v-if="form.mapMarker">
              {{form.mapMarker.lng}},{{form.mapMarker.lat}}
            </el-tag>
            <el-button size="mini" @click="clearMarkerEdit" style="margin-left:8px;">清空标记</el-button>
          </div>
        </el-form-item>
        <el-form-item label="地图权限设置" label-width="90px" class="nowrap-label"><el-input v-model="form.permission" placeholder="JSON格式" type="textarea" :rows="2" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEdit=false">取消</el-button>
        <el-button type="primary" @click="update">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getBranchList, addBranch, updateBranch, deleteBranch } from '@/api/branch';
import { getClanList } from '@/api/clan';
import { getUserList } from '@/api/user';
import { initMap, createMarker, createPolyline, searchPlace } from '@/utils/amap-simple';
let debounceTimer = null;
export default {
  data() {
    return {
      list: [],
      total: 0,
      size: 10,
      current: 1,
      showAdd: false,
      showEdit: false,
      form: {
        clanId: '',
        name: '',
        leaderId: '',
        description: '',
        migrationRoute: [],
        mapMarker: null,
        permission: ''
      },
      clanList: [], // 家族列表
      userList: [], // 用户列表
      migrationMap: null,
      markerMap: null,
      migrationPolyline: null,
      markerObj: null,
      migrationMapEdit: null,
      markerMapEdit: null,
      migrationPolylineEdit: null,
      markerObjEdit: null,
      searchKeywordAdd: '',
      searchResultsAdd: [],
      searchKeywordMarkerAdd: '',
      searchResultsMarkerAdd: [],
      searchKeywordEdit: '',
      searchResultsEdit: [],
      searchKeywordMarkerEdit: '',
      searchResultsMarkerEdit: [],
      debounceTimerAdd: null,
      debounceTimerMarkerAdd: null,
      debounceTimerEdit: null,
      debounceTimerMarkerEdit: null,
    };
  },
  created() {
    this.load();
  },
  methods: {
    // 获取当前位置
    getCurrentPosition() {
      return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0
        });
      });
        },

    // 加载家族列表
    async loadClanList() {
      try {
        const data = await getClanList({ page: 1, size: 1000 }); // 获取所有家族
        this.clanList = data.records || [];
        console.log('加载家族列表成功:', this.clanList);
      } catch (error) {
        console.error('加载家族列表失败:', error);
        this.$message.error('加载家族列表失败');
      }
    },
    // 加载用户列表
    async loadUserList() {
      try {
        const data = await getUserList({ page: 1, size: 1000 }); // 获取所有用户
        this.userList = data.records || [];
        console.log('加载用户列表成功:', this.userList);
      } catch (error) {
        console.error('加载用户列表失败:', error);
        this.$message.error('加载用户列表失败');
      }
    },

    async load(page = 1) {
      this.current = page;
      const data = await getBranchList({ page, size: this.size });
      this.list = data.records;
      this.total = data.total;
      this.size = data.size;
      this.current = data.current;
      this.pages = data.pages; // 可用于显示总页数
    },
    handleSizeChange(newSize) {
      this.size = newSize;
      this.load(1);
    },
    async onShowAdd() {
      this.form = {
        clanId: '',
        name: '',
        leaderId: '',
        description: '',
        migrationRoute: [],
        mapMarker: null,
        permission: ''
      };
      this.showAdd = true;

      // 加载家族和用户列表
      await Promise.all([
        this.loadClanList(),
        this.loadUserList()
      ]);

      // 等待DOM渲染完成后再初始化地图
      await this.$nextTick();
      // 添加延迟确保DOM完全渲染
      setTimeout(async () => {
        await this.initMigrationMap();
        await this.initMarkerMap();
      }, 100);
    },
    async initMigrationMap() {
      try {
        console.log('开始初始化迁徙路线地图...');
        if (this.migrationMap) this.migrationMap.destroy();

        // 检查DOM元素是否存在
        const container = document.getElementById('migrationMap');
        if (!container) {
          console.error('迁徙路线地图容器不存在');
          return;
        }

        // 获取用户当前位置作为默认中心点
        let center = [113, 28]; // 默认湖南
        if (navigator.geolocation) {
          try {
            const position = await this.getCurrentPosition();
            center = [position.coords.longitude, position.coords.latitude];
            console.log('获取到当前位置:', center);
          } catch (error) {
            console.log('无法获取当前位置，使用默认位置');
          }
        }

        console.log('初始化地图，中心点:', center);
        this.migrationMap = await initMap('migrationMap', { zoom: 8, center: center });
        console.log('迁徙路线地图初始化成功');

        this.migrationMap.on('click', async e => {
          this.form.migrationRoute.push({ lng: e.lnglat.lng, lat: e.lnglat.lat });
          await this.drawMigrationRoute();
        });
        await this.drawMigrationRoute();
      } catch (error) {
        console.error('初始化迁徙路线地图失败:', error);
        this.$message.error('地图加载失败，请检查网络连接');
        // 如果地图加载失败，至少显示一个提示
        const container = document.getElementById('migrationMap');
        if (container) {
          container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;">地图加载失败，请刷新页面重试</div>';
        }
      }
    },
    async drawMigrationRoute() {
      if (this.migrationPolyline) this.migrationMap.remove(this.migrationPolyline);
      // 清除旧的迁徙点marker
      if (this.migrationMarkers && Array.isArray(this.migrationMarkers)) {
        this.migrationMarkers.forEach(mk => this.migrationMap.remove(mk));
      }
      this.migrationMarkers = [];
      if (this.form.migrationRoute.length > 1) {
        const path = this.form.migrationRoute.map(p => [p.lng, p.lat]);
        const AMap = window.AMap;
        this.migrationPolyline = new AMap.Polyline({
          path,
          strokeColor: ['#6a82fb', '#fc5c7d', '#ffd803'], // 渐变主色
          strokeWeight: 8,
          strokeOpacity: 0.95,
          isOutline: true,
          outlineColor: '#fff',
          strokeStyle: 'solid',
          showDir: true, // 显示箭头
          lineJoin: 'round',
          lineCap: 'round',
          zIndex: 10
        });
        this.migrationMap.add(this.migrationPolyline);
      }
      // 为每个迁徙点添加带地名的marker
      if (this.form.migrationRoute.length > 0) {
        const AMap = window.AMap;
        this.form.migrationRoute.forEach((point) => {
          const lnglat = [point.lng, point.lat];
          AMap.plugin('AMap.Geocoder', () => {
            const geocoder = new AMap.Geocoder();
            geocoder.getAddress(lnglat, (status, result) => {
              let labelContent = '';
              if (status === 'complete' && result.regeocode) {
                labelContent = `<div class="marker-label">${result.regeocode.formattedAddress}</div>`;
              } else {
                labelContent = `<div class="marker-label">${lnglat[0]},${lnglat[1]}</div>`;
              }
              const marker = new AMap.Marker({
                position: lnglat,
                label: {
                  content: labelContent,
                  direction: 'top'
                }
              });
              this.migrationMap.add(marker);
              this.migrationMarkers.push(marker);
            });
          });
        });
      }
    },
    async clearRoute() {
      this.form.migrationRoute = [];
      await this.drawMigrationRoute();
    },
    async initMarkerMap() {
      try {
        console.log('开始初始化标记地图...');
        if (this.markerMap) this.markerMap.destroy();

        // 检查DOM元素是否存在
        const container = document.getElementById('markerMap');
        if (!container) {
          console.error('标记地图容器不存在');
          return;
        }

        // 获取用户当前位置作为默认中心点
        let center = [113, 28]; // 默认湖南
        if (navigator.geolocation) {
          try {
            const position = await this.getCurrentPosition();
            center = [position.coords.longitude, position.coords.latitude];
            console.log('获取到当前位置:', center);
            // 如果没有设置标记，使用当前位置作为默认标记
            if (!this.form.mapMarker) {
              this.form.mapMarker = { lng: center[0], lat: center[1] };
              console.log('设置默认标记位置:', this.form.mapMarker);
            }
          } catch (error) {
            console.log('无法获取当前位置，使用默认位置');
          }
        }

        console.log('初始化标记地图，中心点:', center);
        this.markerMap = await initMap('markerMap', { zoom: 8, center: center });
        console.log('标记地图初始化成功');

        this.markerMap.on('click', async e => {
          this.form.mapMarker = { lng: e.lnglat.lng, lat: e.lnglat.lat };
          await this.drawMarker();
        });
        await this.drawMarker();
      } catch (error) {
        console.error('初始化标记地图失败:', error);
        this.$message.error('地图加载失败，请检查网络连接');
        // 如果地图加载失败，至少显示一个提示
        const container = document.getElementById('markerMap');
        if (container) {
          container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;">地图加载失败，请刷新页面重试</div>';
        }
      }
    },
    async drawMarker() {
      if (this.markerObj) this.markerMap.remove(this.markerObj);
      if (this.form.mapMarker) {
        const lnglat = [this.form.mapMarker.lng, this.form.mapMarker.lat];
        const AMap = window.AMap;
        AMap.plugin('AMap.Geocoder', () => {
          const geocoder = new AMap.Geocoder();
          geocoder.getAddress(lnglat, (status, result) => {
            let labelContent = '';
            if (status === 'complete' && result.regeocode) {
              labelContent = `<div class="marker-label">${result.regeocode.formattedAddress}</div>`;
            } else {
              labelContent = `<div class="marker-label">${lnglat[0]},${lnglat[1]}</div>`;
            }
            this.markerObj = new AMap.Marker({
              position: lnglat,
              label: {
                content: labelContent,
                direction: 'top'
              }
            });
            this.markerMap.add(this.markerObj);
            this.markerMap.setCenter(lnglat);
          });
        });
      }
    },
    async clearMarker() {
      this.form.mapMarker = null;
      await this.drawMarker();
    },
    // 编辑弹窗地图
    async edit(row) {
      console.log('编辑接收到的数据:', row);

      // 处理从后端接收的数据
      let migrationRoute = [];
      let mapMarker = null;

      // 解析迁徙路线数据
      if (row.migrationRoute) {
        try {
          migrationRoute = JSON.parse(row.migrationRoute);
        } catch (e) {
          console.warn('迁徙路线数据解析失败:', e);
          migrationRoute = [];
        }
      }

      // 解析地图标记数据
      if (row.mapMarker) {
        try {
          mapMarker = JSON.parse(row.mapMarker);
        } catch (e) {
          console.warn('地图标记数据解析失败:', e);
          mapMarker = null;
        }
      }

      this.form = {
        ...row,
        migrationRoute: migrationRoute,
        mapMarker: mapMarker,
        permission: row.permission ? JSON.stringify(row.permission) : ''
      };

      console.log('处理后的表单数据:', this.form);
      this.showEdit = true;

      // 加载家族和用户列表
      await Promise.all([
        this.loadClanList(),
        this.loadUserList()
      ]);

      // 等待DOM渲染完成后再初始化地图
      await this.$nextTick();
      // 添加延迟确保DOM完全渲染
      setTimeout(async () => {
        await this.initMigrationMapEdit();
        await this.initMarkerMapEdit();
      }, 100);
    },
    async initMigrationMapEdit() {
      try {
        if (this.migrationMapEdit) this.migrationMapEdit.destroy();
        // 获取用户当前位置作为默认中心点
        let center = [113, 28]; // 默认湖南
        if (navigator.geolocation) {
          try {
            const position = await this.getCurrentPosition();
            center = [position.coords.longitude, position.coords.latitude];
          } catch (error) {
            console.log('无法获取当前位置，使用默认位置');
          }
        }

        this.migrationMapEdit = await initMap('migrationMapEdit', { zoom: 8, center: center });
        this.migrationMapEdit.on('click', async e => {
          this.form.migrationRoute.push({ lng: e.lnglat.lng, lat: e.lnglat.lat });
          await this.drawMigrationRouteEdit();
        });
        await this.drawMigrationRouteEdit();
      } catch (error) {
        console.error('初始化编辑迁徙路线地图失败:', error);
        this.$message.error('地图加载失败，请检查网络连接');
      }
    },
    async drawMigrationRouteEdit() {
      if (this.migrationPolylineEdit) this.migrationMapEdit.remove(this.migrationPolylineEdit);
      // 清除旧的迁徙点marker
      if (this.migrationMarkersEdit && Array.isArray(this.migrationMarkersEdit)) {
        this.migrationMarkersEdit.forEach(mk => this.migrationMapEdit.remove(mk));
      }
      this.migrationMarkersEdit = [];
      if (this.form.migrationRoute.length > 1) {
        const path = this.form.migrationRoute.map(p => [p.lng, p.lat]);
        const AMap = window.AMap;
        this.migrationPolylineEdit = new AMap.Polyline({
          path,
          strokeColor: ['#6a82fb', '#fc5c7d', '#ffd803'],
          strokeWeight: 8,
          strokeOpacity: 0.95,
          isOutline: true,
          outlineColor: '#fff',
          strokeStyle: 'solid',
          showDir: true,
          lineJoin: 'round',
          lineCap: 'round',
          zIndex: 10
        });
        this.migrationMapEdit.add(this.migrationPolylineEdit);
      }
      // 为每个迁徙点添加带地名的marker
      if (this.form.migrationRoute.length > 0) {
        const AMap = window.AMap;
        this.form.migrationRoute.forEach((point) => {
          const lnglat = [point.lng, point.lat];
          AMap.plugin('AMap.Geocoder', () => {
            const geocoder = new AMap.Geocoder();
            geocoder.getAddress(lnglat, (status, result) => {
              let labelContent = '';
              if (status === 'complete' && result.regeocode) {
                labelContent = `<div class="marker-label">${result.regeocode.formattedAddress}</div>`;
              } else {
                labelContent = `<div class="marker-label">${lnglat[0]},${lnglat[1]}</div>`;
              }
              const marker = new AMap.Marker({
                position: lnglat,
                label: {
                  content: labelContent,
                  direction: 'top'
                }
              });
              this.migrationMapEdit.add(marker);
              this.migrationMarkersEdit.push(marker);
            });
          });
        });
      }
    },
    async clearRouteEdit() {
      this.form.migrationRoute = [];
      await this.drawMigrationRouteEdit();
    },
    async initMarkerMapEdit() {
      try {
        if (this.markerMapEdit) this.markerMapEdit.destroy();
        // 获取用户当前位置作为默认中心点
        let center = [113, 28]; // 默认湖南
        if (navigator.geolocation) {
          try {
            const position = await this.getCurrentPosition();
            center = [position.coords.longitude, position.coords.latitude];
            // 如果没有设置标记，使用当前位置作为默认标记
            if (!this.form.mapMarker) {
              this.form.mapMarker = { lng: center[0], lat: center[1] };
            }
          } catch (error) {
            console.log('无法获取当前位置，使用默认位置');
          }
        }

        this.markerMapEdit = await initMap('markerMapEdit', { zoom: 8, center: center });
        this.markerMapEdit.on('click', async e => {
          this.form.mapMarker = { lng: e.lnglat.lng, lat: e.lnglat.lat };
          await this.drawMarkerEdit();
        });
        await this.drawMarkerEdit();
      } catch (error) {
        console.error('初始化编辑标记地图失败:', error);
        this.$message.error('地图加载失败，请检查网络连接');
      }
    },
    async drawMarkerEdit() {
      if (this.markerObjEdit) this.markerMapEdit.remove(this.markerObjEdit);
      if (this.form.mapMarker) {
        const lnglat = [this.form.mapMarker.lng, this.form.mapMarker.lat];
        const AMap = window.AMap;
        AMap.plugin('AMap.Geocoder', () => {
          const geocoder = new AMap.Geocoder();
          geocoder.getAddress(lnglat, (status, result) => {
            let labelContent = '';
            if (status === 'complete' && result.regeocode) {
              labelContent = `<div class="marker-label">${result.regeocode.formattedAddress}</div>`;
            } else {
              labelContent = `<div class="marker-label">${lnglat[0]},${lnglat[1]}</div>`;
            }
            this.markerObjEdit = new AMap.Marker({
              position: lnglat,
              label: {
                content: labelContent,
                direction: 'top'
              }
            });
            this.markerMapEdit.add(this.markerObjEdit);
            this.markerMapEdit.setCenter(lnglat);
          });
        });
      }
    },
    async clearMarkerEdit() {
      this.form.mapMarker = null;
      await this.drawMarkerEdit();
    },
    async add() {
      console.log('提交前的表单数据:', this.form);
      // 数据验证
      if (!this.form.name || !this.form.clanId) {
        this.$message.error('请填写分支名称和家族ID');
        return;
      }
      let payload = { ...this.form };
      if (payload.clanId) payload.clanId = parseInt(payload.clanId);
      if (payload.leaderId) payload.leaderId = parseInt(payload.leaderId);
      if (payload.permission) {
        try { payload.permission = JSON.parse(payload.permission); } catch(e) { payload.permission = {}; }
      }
      if (payload.migrationRoute && !Array.isArray(payload.migrationRoute)) payload.migrationRoute = [];
      if (payload.mapMarker && typeof payload.mapMarker !== 'object') payload.mapMarker = null;
      if (payload.migrationRoute && payload.migrationRoute.length > 0) payload.migrationRoute = JSON.stringify(payload.migrationRoute); else payload.migrationRoute = null;
      if (payload.mapMarker) payload.mapMarker = JSON.stringify(payload.mapMarker); else payload.mapMarker = null;
      console.log('提交到后端的数据:', payload);
      try {
        await addBranch(payload);
        this.$message.success('分支添加成功');
        this.showAdd = false;
        this.load();
      } catch (error) {
        console.error('添加分支失败:', error);
        this.$message.error('添加分支失败，请重试');
      }
    },
    async update() {
      console.log('更新前的表单数据:', this.form);
      let payload = { ...this.form };
      if (payload.clanId) payload.clanId = parseInt(payload.clanId);
      if (payload.leaderId) payload.leaderId = parseInt(payload.leaderId);
      if (payload.permission) {
        try { payload.permission = JSON.parse(payload.permission); } catch(e) { payload.permission = {}; }
      }
      if (payload.migrationRoute && !Array.isArray(payload.migrationRoute)) payload.migrationRoute = [];
      if (payload.mapMarker && typeof payload.mapMarker !== 'object') payload.mapMarker = null;
      if (payload.migrationRoute && payload.migrationRoute.length > 0) payload.migrationRoute = JSON.stringify(payload.migrationRoute); else payload.migrationRoute = null;
      if (payload.mapMarker) payload.mapMarker = JSON.stringify(payload.mapMarker); else payload.mapMarker = null;
      console.log('更新到后端的数据:', payload);
      try {
        await updateBranch(payload);
        this.$message.success('分支更新成功');
        this.showEdit = false;
        this.load();
      } catch (error) {
        console.error('更新分支失败:', error);
        this.$message.error('更新分支失败，请重试');
      }
    },
    async remove(row) {
      try {
        await this.$confirm('确定要删除该分支吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await deleteBranch(row.id);
        this.$message.success('分支删除成功');
        this.load();
      } catch (e) {
        if (e !== 'cancel') {
          this.$message.error('分支删除失败');
        }
      }
    },
    goDetail(row) {
      this.$router.push({ path: `/branch/detail/${row.id}` });
    },
    // 新增分支-迁徙路线
    onSearchInputAddDebounced() {
      clearTimeout(this.debounceTimerAdd);
      this.debounceTimerAdd = setTimeout(this.onSearchInputAdd, 300);
    },
    async onSearchInputAdd() {
      console.log('输入内容：', this.searchKeywordAdd);
      if (!this.searchKeywordAdd) { this.searchResultsAdd = []; return; }
      try {
        const res = await searchPlace(this.searchKeywordAdd);
        console.log('地名联想结果：', res);
        this.searchResultsAdd = res;
      } catch (e) {
        this.searchResultsAdd = [];
        console.error('地名搜索失败', e);
      }
    },
    async onSelectPlaceAdd(item) {
      if (this.migrationMap) {
        this.migrationMap.setZoomAndCenter(16, [item.location.lng, item.location.lat]);
        this.form.migrationRoute.push({ lng: item.location.lng, lat: item.location.lat });
        await this.drawMigrationRoute();
      }
      this.searchResultsAdd = [];
      this.searchKeywordAdd = item.name;
    },
    // 新增分支-地图标记
    onSearchInputMarkerAddDebounced() {
      clearTimeout(this.debounceTimerMarkerAdd);
      this.debounceTimerMarkerAdd = setTimeout(this.onSearchInputMarkerAdd, 300);
    },
    async onSearchInputMarkerAdd() {
      console.log('输入内容：', this.searchKeywordMarkerAdd);
      if (!this.searchKeywordMarkerAdd) { this.searchResultsMarkerAdd = []; return; }
      try {
        const res = await searchPlace(this.searchKeywordMarkerAdd);
        console.log('地名联想结果：', res);
        this.searchResultsMarkerAdd = res;
      } catch (e) {
        this.searchResultsMarkerAdd = [];
        console.error('地名搜索失败', e);
      }
    },
    async onSelectMarkerPlaceAdd(item) {
      if (this.markerMap) {
        this.markerMap.setZoomAndCenter(16, [item.location.lng, item.location.lat]);
        this.form.mapMarker = { lng: item.location.lng, lat: item.location.lat };
        await this.drawMarker();
      }
      this.searchResultsMarkerAdd = [];
      this.searchKeywordMarkerAdd = item.name;
    },
    // 编辑分支-迁徙路线
    onSearchInputEditDebounced() {
      clearTimeout(this.debounceTimerEdit);
      this.debounceTimerEdit = setTimeout(this.onSearchInputEdit, 300);
    },
    async onSearchInputEdit() {
      console.log('输入内容：', this.searchKeywordEdit);
      if (!this.searchKeywordEdit) { this.searchResultsEdit = []; return; }
      try {
        const res = await searchPlace(this.searchKeywordEdit);
        console.log('地名联想结果：', res);
        this.searchResultsEdit = res;
      } catch (e) {
        this.searchResultsEdit = [];
        console.error('地名搜索失败', e);
      }
    },
    async onSelectPlaceEdit(item) {
      if (this.migrationMapEdit) {
        this.migrationMapEdit.setZoomAndCenter(16, [item.location.lng, item.location.lat]);
        this.form.migrationRoute.push({ lng: item.location.lng, lat: item.location.lat });
        await this.drawMigrationRouteEdit();
      }
      this.searchResultsEdit = [];
      this.searchKeywordEdit = item.name;
    },
    // 编辑分支-地图标记
    onSearchInputMarkerEditDebounced() {
      clearTimeout(this.debounceTimerMarkerEdit);
      this.debounceTimerMarkerEdit = setTimeout(this.onSearchInputMarkerEdit, 300);
    },
    async onSearchInputMarkerEdit() {
      console.log('输入内容：', this.searchKeywordMarkerEdit);
      if (!this.searchKeywordMarkerEdit) { this.searchResultsMarkerEdit = []; return; }
      try {
        const res = await searchPlace(this.searchKeywordMarkerEdit);
        console.log('地名联想结果：', res);
        this.searchResultsMarkerEdit = res;
      } catch (e) {
        this.searchResultsMarkerEdit = [];
        console.error('地名搜索失败', e);
      }
    },
    async onSelectMarkerPlaceEdit(item) {
      if (this.markerMapEdit) {
        this.markerMapEdit.setZoomAndCenter(16, [item.location.lng, item.location.lat]);
        this.form.mapMarker = { lng: item.location.lng, lat: item.location.lat };
        await this.drawMarkerEdit();
      }
      this.searchResultsMarkerEdit = [];
      this.searchKeywordMarkerEdit = item.name;
    },
  }
};
</script>
<style scoped>
.system-bg {
  min-height: 80vh;
  background: linear-gradient(135deg, #f4f6fa 60%, #e0e7ff 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 0;
  animation: fadeIn 0.8s;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(30px);}
  to { opacity: 1; transform: none;}
}
.user-card {
  width: 1100px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.10);
  background: rgba(255,255,255,0.95);
  transition: box-shadow 0.3s;
}
.card-header-vertical {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  padding-bottom: 8px;
}
.header-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
}
.header-btn-group {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background: none;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
}
.header-btn-group.right {
  justify-content: flex-end;
}
.header-btn-group .el-button {
  margin-right: 8px;
  height: 34px;
  font-size: 15px;
  padding: 0 18px;
  display: flex;
  align-items: center;
}
.header-btn-group .el-button:last-child {
  margin-right: 0;
}
.add-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
}
.add-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}
.user-table {
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 18px;
}
.user-table ::v-deep .el-table__row:hover {
  background: #f0f7ff !important;
  transition: background 0.2s;
}
.edit-btn {
  background: #fff;
  border: 1px solid #6a82fb;
  color: #6a82fb;
  /* margin-right: 5px; */
  transition: all 0.2s;
  /* min-width: 62px; */
}
.edit-btn:hover {
  background: #6a82fb;
  color: #fff;
}
.delete-btn {
  background: #fff;
  border: 1px solid #fc5c7d;
  color: #fc5c7d;
  transition: all 0.2s;
}
.delete-btn:hover {
  background: #fc5c7d;
  color: #fff;
}
.detail-btn {
  background: #fff;
  border: 1px solid #909399;
  color: #606266;
  border-radius: 6px;
  transition: all 0.2s;
}
.detail-btn:hover {
  background: #f4f6fa;
  color: #409EFF;
  border-color: #409EFF;
}
.user-pagination {
  margin-top: 18px;
  text-align: right;
}
.user-pagination ::v-deep .el-pager li {
  border-radius: 6px;
  transition: background 0.2s;
}
.user-pagination ::v-deep .el-pager li.active {
  background: #6a82fb;
  color: #fff;
}
.fade-dialog ::v-deep .el-dialog__wrapper {
  animation: fadeIn 0.4s;
}
.custom-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  background: #fafdff;
  padding-bottom: 0;
}
.dialog-form {
  padding: 12px 0 0 0;
}
.dialog-form ::v-deep .el-form-item {
  margin-bottom: 22px;
}
.dialog-footer {
  text-align: right;
  padding: 8px 0 8px 0;
}
.dialog-footer .el-button {
  min-width: 80px;
  border-radius: 6px;
  font-weight: 500;
  margin-left: 8px;
}
.dialog-footer .el-button--primary {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
}
.dialog-footer .el-button--primary:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}
.map-search-box {
  position: relative;
  width: 350px;
  margin-bottom: 4px;
}
.map-search-input {
  width: 100%;
  padding: 7px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  outline: none;
  font-size: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  transition: border 0.2s;
}
.map-search-input:focus {
  border-color: #409EFF;
}
.suggest-list {
  position: absolute;
  left: 0;
  right: 0;
  top: 38px;
  z-index: 99;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
  max-height: 220px;
  overflow-y: auto;
  margin: 0;
  padding: 0;
  list-style: none;
}
.suggest-list li {
  padding: 7px 12px;
  cursor: pointer;
  font-size: 15px;
}
.suggest-list li:hover {
  background: #f0f7ff;
  color: #409EFF;
}
.suggest-list .name {
  font-weight: 500;
}
.suggest-list .desc {
  font-size: 12px;
  color: #888;
  margin-top: 2px;
}
.marker-label {
  background: rgba(64,158,255,0.95);
  color: #fff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  white-space: nowrap;
}
.nowrap-label ::v-deep .el-form-item__label {
  white-space: nowrap;
}
.action-btn-group {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 12px;
}
.edit-btn, .delete-btn, .detail-btn {
  min-width: 55px;
}
</style>
